package br.com.agenda.support.contato;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;
import org.primefaces.event.SelectEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.WebApplicationContext;

import br.com.agenda.model.ContatoEntity;
import br.com.agenda.model.repositories.IContatoRepository;
import br.com.agenda.model.utils.BaseBeans;

@Scope(value = WebApplicationContext.SCOPE_SESSION)
@Named(value = "contatoMB")
public class ContatoMB extends BaseBeans {

	private static final long serialVersionUID = 1L;
	
	private static final Logger logger = Logger.getLogger(ContatoMB.class);
	
	@Inject
	private IContatoRepository contatoRepository;
	
	private List<ContatoEntity> contatos;
	
	private ContatoEntity selectedContato;
	
	private Long id;
	
	public ContatoMB(){
		
	}
	
	public void onLoad(){
		this.contatos = this.contatoRepository.findAll();
	}
	
	public List<ContatoEntity> getContatos(){
		return this.contatos;
	}
	
	public Long getID(){
		return this.id;
	}
	
	public void setID(Long id){
		this.id = id;
	}
	
	public void delete(){
		if(this.selectedContato != null){
			this.contatoRepository.delete(this.selectedContato.getId());
		}
	}
	
	public void selectContato(SelectEvent evt){
		try{
			if(evt.getObject() != null){
				this.selectedContato = (ContatoEntity) evt.getObject();
			}else{
				this.selectedContato = null;
			}
		}catch(Exception e){
			this.selectedContato = null;
			
			logger.error(e.getMessage(), e);
		}
	}
	
	public void unselectContato(){
		this.selectedContato = null;
	}
	
	public ContatoEntity getSelectedContato(){
		return this.selectedContato;
	}
	
	public void setSelectedContato(ContatoEntity selectedContato){
		this.selectedContato = selectedContato;
	}
}
